package com.luban.springboot.handler;

import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;

import com.luban.springboot.pojo.User;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Component
public class UserHandler {

	public Mono<ServerResponse> getInfo(ServerRequest serverRequest) {
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
                .body(Flux.just("班友你好，欢迎进入webflux响应式Web编程"), String.class);
    }
	
	public Mono<ServerResponse> getList(ServerRequest serverRequest) {
        List<User> users = Arrays.asList(
        		User.builder().id(15).type("男").userName("小班友").build(),
        		User.builder().id(25).type("女").userName("小书包").build(),
        		User.builder().id(35).type("男").userName("小鱼儿").build());
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(Flux.just(users), List.class);
    }
	
	public Mono<ServerResponse> getRealMsg(ServerRequest serverRequest) {
        return ServerResponse.ok().contentType(MediaType.TEXT_EVENT_STREAM)
                .body(Flux.interval(Duration.ofSeconds(1))
                      .map(a -> "服务端推送的随机数：" + new Random().ints(1, (999 + 1)).findFirst().getAsInt()),String.class);
    }
}
